<template>
  <div class="customer-service-list">
    <div class="main-container">
      <div class="top-bar">
        <el-button type="primary" @click="dialogFormVisible = true" >添加客服</el-button>
      </div>
      <div class="content">
        <el-table v-loading.fullscreen.lock="loading" v-show="tableData.length > 0" stripe :data="filterTableData" style="width: 100%" >
          <el-table-column label="账号" prop="name" />
          <el-table-column label="昵称" prop="nickname" />
          <el-table-column label="创建时间" prop="createTime" />
          <el-table-column align="right">
            <template #header>
              <el-input v-model="search" placeholder="客服搜索" />
            </template>
            <template #default="scope">
              <el-button @click="handleEdit(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-button
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-show="!tableData || tableData.length === 0" description="暂无数据" />
      </div>
      <el-dialog v-model="dialogFormVisible" title="添加客服" width="500" @close="handleCancelAdd">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="账号" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" autocomplete="off" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" autocomplete="off" placeholder="请输入昵称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelAdd">取消</el-button>
            <el-button type="primary" @click="handleAddCustomerService(formRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogEditFormVisible" title="编辑客服" width="500" @close="handleCancelEdit">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef">
          <el-form-item label="账号">
            <el-input v-model="editForm.name" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" autocomplete="off" placeholder="不填代表不修改该项" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" autocomplete="off" placeholder="不填代表不修改该项" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelEdit">取消</el-button>
            <el-button type="primary" @click="handleEditCustomerService(editFormRef)">提交</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="centerDialogVisible" title="提示" width="300" center>
        <div class="delete-text">
          是否删除客服 {{ currentSelectedUser ? currentSelectedUser.nickname : '' }}
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelDelete">取消</el-button>
            <el-button type="primary" @click="handleDeleteClick">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, reactive } from 'vue'
import useUsersStore from '@/store/users/users'
import { format, parseISO } from 'date-fns'

const usersStore = useUsersStore()
const search = ref('')
const formRef = ref(null)
const editFormRef = ref(null)
const currentSelectedUser = ref(null)
const isEdit = ref(false)
const loading = ref(false)

const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.nickname.toLowerCase().includes(search.value.toLowerCase())
  )
)

const dialogEditFormVisible = ref(false)

const editForm = reactive({
  name: '',
  password: '',
  nickname: ''
})

const editRules = reactive({
  password: [
    { min: 6, max: 20, message: '长度在6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ]
})

const handleCancelEdit = () => {
  isEdit.value = false
  currentSelectedUser.value = null
  dialogEditFormVisible.value = false
  editForm.name = ''
  editForm.password = ''
  editForm.nickname = ''
}

const handleEditCustomerService = (editFormEl) => {
  const editValidForm = () => {
    return new Promise((resolve, reject) => {
      editFormEl.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    })
  }

  editValidForm().then(() => {
    const params = {
      id: currentSelectedUser.value.id,
      account: editForm.name
    }
    if (!editForm.nickname && !editForm.password) {
      // 无更改项
      console.log('无更改项，不做修改处理');
      ElMessage.error('请填写要修改的信息后再提交 ~')
      return;
    }
    if (editForm.password) {
      params.password = editForm.password
    }
    if (editForm.nickname) {
      params.nickname = editForm.nickname
    }
    loading.value = true
    usersStore.updateCustomerService(params).then((res) => {
      loading.value = false
      console.log(res)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '修改客服信息成功 ~'
        })
        currentSelectedUser.value = null
        isEdit.value = false
        dialogEditFormVisible.value = false
        editForm.name = ''
        // 刷新数据
        loadUserList()
      } else {
        ElMessage.error(`修改客服信息失败 ${res.message}`)
      }
    }).catch((err) => {
      ElMessage.error('修改客服信息失败')
    })
  }).catch((err) => {
    console.log(err)
  })
}

const handleEdit = (index, row) => {
  currentSelectedUser.value = row
  editForm.name = row.name
  isEdit.value = true
  dialogEditFormVisible.value = true
}

const centerDialogVisible = ref(false)

const handleDelete = (index, row) => {
  currentSelectedUser.value = row
  centerDialogVisible.value = true
}

const tableData = ref([])

const dialogFormVisible = ref(false)

const form = reactive({
  name: '',
  password: '123456',
  nickname: ''
})

const rules = reactive({
  name: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ]
})

const handleCancelAdd = () => {
  dialogFormVisible.value = false
  form.name = ''
  form.password = '123456'
  form.nickname = ''
}

const handleAddCustomerService = (formEl) => {
  const validateForm = () => {
    return new Promise((resolve, reject) => {
      formEl.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    })
  }

  validateForm().then(() => {
    loading.value = true
    usersStore.createCustomerService({
      account: form.name,
      nickname: form.nickname,
      password: form.password,
      roleId: 2
    }).then((res) => {
      loading.value = false
      console.log(res)
      if (res.code === 0) {
        const user = res.data
        user.createTime = format(parseISO(user.createTime), 'yyyy-MM-dd HH:mm:ss')
        tableData.value.unshift(user)
        dialogFormVisible.value = false
      } else {
        ElMessage.error(`添加客服失败 ${res.message}`)
      }
    }).catch((err) => {
      console.log(err)
      ElMessage.error(`添加客服失败 ${err.message}`)
    })
  }).catch((err) => {
    ElMessage.error('请完善客服信息')
  })
}

const handleCancelDelete = () => {
  currentSelectedUser.value = null
  centerDialogVisible.value = false
}

const handleDeleteClick = () => {
  loading.value = true
  console.log('currentSelectedUser.value.id: ', currentSelectedUser.value.id)
  usersStore.deleteCustomerService(currentSelectedUser.value.id).then((res) => {
    loading.value = false
    if (res.code === 0) {
      tableData.value = tableData.value.filter((user) => user.id !== currentSelectedUser.value.id)
      ElMessage({
        type: 'success',
        message: '删除成功 ~'
      })
      currentSelectedUser.value = null
      centerDialogVisible.value = false
    } else {
      ElMessage.error(`删除客服失败 ${res.message}`)
    }
  })
}

const loadUserList = () => {
  loading.value = true
  usersStore.getCustomerServices({
    limit: 20,
    offset: 0,
    roleId: 2
  }).then((res) => {
    if (res.code === 0) {
      loading.value = false
      tableData.value = res.data.map((user) => {
        return {
          ...user,
          createTime: format(parseISO(user.createTime), 'yyyy-MM-dd HH:mm:ss')
        }
      })
    }
    console.log(res)
  }).catch((err) => {
    if (err) console.log(err)
  })
}

onMounted(() => {
  loadUserList()
})

</script>

<style lang="scss" scoped>

.customer-service-list {
  .main-container {
    .top-bar {
      padding: 10px 10px 20px;
      border-bottom: 1px solid #ededed;
    }
    .content {
      margin-top: 20px;
    }
    .delete-text {
      padding: 20px 10px;
      font-size: 16px;
      text-align: center;
    }
  }
}

</style>